import  hashlib
import os
import tarfile
import pickle
from time import strftime

def check_md5(fname):
    m = hashlib.md5()
    with open(fname,'rb') as fobj:
        while 1:
            data=fobj.read(4096)
            if not data:
                break
            m.update(data)
    return m.hexdigest()

def full_backup(src, dst, md5file):
    '将整个目录打tar包即可'
    fname= '%s_full_%s.tar.gz' % (os.path.basename(src),strftime('%Y%m%d'))
    fname=os.path.join(dst,fname)

    #备份
    tar = tarfile.open(fname, 'w:gz')
    tar.add(src)
    tar.close()

    #计算每个文件的md5值
    md5dict = {}   #key是文件名，val是md5值
    for path,folders,files in os.walk(src):
        for file in files:
            key = os.path.join(path,file)
            md5dict[key] = check_md5(key)
    #将md5值写入md5file:
    with open(md5file,'wb') as fobj:
        pickle.dump(md5file,fobj)

def incr_backup(src, dst, md5file):
    '增量备份'
    '拼接出备份文件的绝对路径'
    fname = '%s_incr_%s.tar.gz' % (os.path.basename(src), strftime('%Y%m%d'))
    fname = os.path.join(dst, fname)

    #计算每个文件的md5值
    md5dict = {}  # key是文件名，val是md5值
    for path, folders, files in os.walk(src):
        for file in files:
            key = os.path.join(path, file)
            md5dict[key] = check_md5(key)

    #取出前一天的md5值
    with open(md5file,'rb') as fobj:
        old_md5  = pickle.load(fobj)

    #查找新文件的改动的文件进行备份
    tar = tarfile.open(fname,'w:gz')
    for key in md5file:
        if old_md5.get(key) != md5dict[key]:
            tar.add(key)
    tar.close()

    #更新md5file：
    with open(md5file,'wb') as fobj:
        pickle.dump(md5file,fobj)
if __name__ == '__main__':
    #mkdir -p //tmp/demo/backup
    #cp -r /etc/security /tmp/demo
    src = '/tmp/demo/security'
    dst = '/tmp/demo/backup'
    md5file = '/tmp/demo/backup/md5.data'
    if strftime('%a') == 'Mon':
        full_backup(src, dst, md5file)
    else:
        incr_backup(src, dst, md5file)


#hashlib
# md5    10：30
#tarfile    打目录
#os.walk    分解文件名
#time.strftime 印有日期    主程序有周几
